package com.google.appengine.a4ieve.servlets.resources;

import com.google.appengine.a4ieve.Const;
import com.google.appengine.a4ieve.entities.CuratorWrapper;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

class AddCuratorServant implements Servant {

    private static final Logger LOG = Logger.getLogger(AddCuratorServant.class.getName());
    private static final String NICKNAME = "googleNickName";
    private static final String STUDENT_GROUP = "group";

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp){
        DatastoreService service = DatastoreServiceFactory.getDatastoreService();
        String userId = req.getParameter(NICKNAME);
        String groupId = req.getParameter(STUDENT_GROUP);
        if (userId == null && groupId == null) {
            JSONObject request = (JSONObject)req.getAttribute(Const.INNER_JSON);
            userId = request.getString(NICKNAME);
            groupId = request.getString(STUDENT_GROUP);
        }
        CuratorWrapper curatorObject = new CuratorWrapper.CuratorBuilder().googleId(userId.toLowerCase()).
                groupId(groupId).build();
        Entity curator = curatorObject.getEntity();
        service.put(curator);
        try {
            Const.SUCCESS_OBJECT.write(resp.getWriter());
        } catch (IOException e) {
            LOG.severe("Error while writing response " + e);
        }
    }
}
